<template>
  <section class="todoapp">
    <TodoHeader @add="addList"></TodoHeader>
    <!-- This section should be hidden by default and shown when there are todos -->
    <TodoMain
      :list="list2"
      @del="delList"
      @state="handelstate"
      @changeAll="handleAll"
    ></TodoMain>
    <!-- This footer should be hidden by default and shown when there are todos -->
    <TodoFooter
      :list="list"
      :flag="flag"
      @delCompleted="clearCompleted"
      @changeFlag="
        (val) => {
          flag = val;
        }
      "
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from "@/components/TodoHeader.vue";
import TodoMain from "@/components/TodoMin.vue";
import TodoFooter from "@/components/TodoFooter.vue";
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 12, name: "吃饭", isDone: false },
      //   { id: 14, name: "听歌", isDone: true },
      //   { id: 23, name: "洗澡", isDone: true },
      //   { id: 34, name: "睡觉", isDone: false },
      //   { id: 35, name: "游戏", isDone: false },
      // ],
      list: JSON.parse(localStorage.getItem("todo")) || [],
      flag: 1, // 1 显示全部任务； 2 显示进行中； 3 显示已完成
    };
  },
  // 计算属性
  computed: {
    list2() {
      if (this.flag === 1) {
        return this.list;
      } else if (this.flag === 2) {
        return this.list.filter((item) => item.isDone === false);
      } else {
        return this.list.filter((item) => item.isDone === true);
      }
    },
  },

  // 监听器
  watch: {
    // list(val) {
    //   // val 表示变化后得值
    //   localStorage.setItem("todo", JSON.stringify(val));
    // },

    // 对象格式
    list: {
      handler(val) {
        localStorage.setItem("todo", JSON.stringify(val));
      },
    },
  },

  methods: {
    // 全选
    handleAll(val) {
      this.list.forEach((item) => {
        item.isDone = val;
      });
    },
    // 清除已完成
    clearCompleted() {
      this.list = this.list.filter((item) => item.isDone === false);
    },
    // 改变状态
    handelstate(id) {
      // this.list.forEach(item => {
      //   if (item.id === id) {
      //     item.isDone = !item.isDone
      //   }
      // })
      const row = this.list.find((item) => item.id === id);
      row.isDone = !row.isDone;
    },
    // 删除
    delList(id) {
      console.log(id);
      this.list = this.list.filter((item) => item.id !== id);
    },
    // 添加
    addList(todoname) {
      this.list.unshift({
        id: Date.now(),
        name: todoname,
        isDone: false,
      });
    },
  },
};
</script>

<style></style>
